package com.zking.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zking.dto.OrderDto;
import com.zking.dto.common.PageDto;
import com.zking.dto.common.ResultDto;
import com.zking.entity.Order;
import com.zking.service.IOrderService;
import com.zking.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/order")
@RequiredArgsConstructor
@CrossOrigin
public class OrderController {
    private final IUserService userService;
    private final IOrderService orderService;
    
    public static final int PAGE_SIZE = 3;
    
    @GetMapping("search") // get - 搜索，获取数据
    public ResultDto<PageDto<OrderDto>> search(OrderDto orderDto,
                                               @RequestParam(name = "page", required = false, defaultValue = "1") int pageNum,
                                               @RequestParam(name = "size", required = false, defaultValue = PAGE_SIZE + "") int pageSize) {
        Page<Order> page = orderService.search(orderDto, pageNum, pageSize);
        PageDto<OrderDto> pageDto = PageDto.fromPage(page, OrderDto::fromOrder);
        return ResultDto.success(pageDto);
    }
    
    @PostMapping // 创建，不能重复发送
    public ResultDto<Void> create(@RequestBody OrderDto orderDto) {
        Order order = OrderDto.toOrder(orderDto);
        order.setUserId(1); // 需要根据当前登录用户获取他的ID
        boolean saved = orderService.save(order);
        return saved ? ResultDto.success(null) : ResultDto.fail(400);
    }
    
    @DeleteMapping// 删除操作
    public ResultDto<Void> delete(@RequestParam int id) {
        boolean removed = orderService.removeById(id);
        if (! removed) {
            throw new RuntimeException("删除666");
        }
        return removed ? ResultDto.success(null) : ResultDto.fail(400);
    }
    
    @PutMapping // 修改
    public ResultDto<Void> delete(OrderDto orderDto) {
        Order order = OrderDto.toOrder(orderDto);
        boolean updated = orderService.updateById(order);
        return updated ? ResultDto.success(null) : ResultDto.fail(400);
    }
}
